package com.yc.zyz.servlet;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.yc.mybatis.damai.MyBatisHelper;
import com.yc.zyz.entity.User;
import com.yc.zyz.mapper.UserMapper;
import com.yc.zyz.util.Utils;
import com.yc.zyz.vo.Result;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/7/28
 * Email haijunzhou@hnit.edu.cn
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        if(name==null || name.isBlank()){
            Utils.print(resp, new Result(0,"请输入账号!",null));
            return;
        }
        if(pwd==null || pwd.isBlank()){
            Utils.print(resp, new Result(0,"请输入密码!",null));
            return;
        }
        SqlSession session = MyBatisHelper.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getName, name);
        lqw.eq(User::getPwd, pwd);
        User user = mapper.selectOne(lqw);
        if(user == null){
            Utils.print(resp, new Result(0,"用户名或密码错误!",null));
            return;
        }
        req.getSession().setAttribute("loginedUser", user);
        Utils.print(resp, new Result(1,"登录成功!",user));

        session.close();
    }

}
